<?php

use think\Db;


if (!function_exists('generate_order_id'))
{
    /*
     * 根据 ID 生成订单号
     * */
    function generate_order_id($user_id)
    {
        return date('mdHis').rand(100,999).(10000-$user_id);   //  生成随机订单
    }

}

if (!function_exists('create_order')){
    /**
     * 生成订单
     *
     * @param int $user_id 购买者id
     * @param int $owner_id 拥有者id
     * @param double $cash 交易现金额
     * @param double $coin 交易币额
     * @param int $order_type 云币交易类型
     * @param int $cash_type 现金交易类型
     * @param string $detail 交易名称/标题
     * @param array $extend 额外字段
     * @param array $user_data 用户表要修改的数据
     * @return string $order_id 生成的订单号
     */
    function create_order($user_id,$owner_id,$cash,$coin,$order_type,$cash_type,$detail,$extend = [],$user_data = []){

        $order_id =  date('mdHis').rand(100,999).(10000-$user_id);   //  生成随机订单
        $time = time();

        //  云币订单表记录
        $order = new \app\admin\model\Order();
        $data = [
            'order_id'  => $order_id,
            'user_id'   => $user_id,
            'owner_id'  => $owner_id,
            'cash'      => $cash,
            'coin'      => $coin,
            'time'      => $time,
            'type'      => $order_type,
            'detail'    => $detail,
        ];
        $data = array_merge($data,$extend);

        //  现金交易表记录
        $cash_log = new \app\common\model\CashLog();
        $cdata = [
            'user_id'   => $user_id,
            'value'     => $cash,
            'detail'    => $detail,
            'type'      => $cash_type,
            'time'      => $time,
            'order_id'  => $order_id
        ];
        $cdata = array_merge($cdata,$extend);

        // 启动事务保存
        Db::startTrans();
        try{
            $order->allowField(true)->data($data)->save();
            $cash_log->allowField(true)->data($cdata)->save();
            //  更新用户表
            $user = \app\common\model\User::get($user_id);
            $user->data($user_data)->save();
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        return $order_id;
    }
}

if (function_exists('success_order'))
{
    /*
     * 认筹成功后奖励
     * */
    function success_order($order_id)
    {
        $order = \app\admin\model\Order::get($order_id);
        //  查找对应订单
        if (!$order) return false;
        $uid = $order->user_id;
    }
}

